<!-- 我的结构树 -->

<template>
  <div v-if="param.subSystemId" class="MyTree">
    <div class="MyTree-title">
      <i class="el-icon-arrow-left" @click="toBack" />
      <span>{{ CORE.dict(CORE.DICT.SUB_SYSTEM, param.subSystemId) }}</span>
    </div>

    <EasyTree
      v-model="selectParam.areaId"
      class="MyTree-tree"
      :tree="deviceTree"
      :field="['children', 'id', 'name']"
      filterTip="搜索"
      @change="toChange"
    >
      <template #default="{ data, nodeClass }">
        <div :class="nodeClass">
          <div v-if="data.device"><img :src="deviceImg" /> {{ data.name }}</div>
          <div v-else>{{ data.name }}</div>
        </div>
      </template>
    </EasyTree>
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import MyMap from '../MyMap'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MyTree',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb(), CORE.mixTree(), CORE.mixSelect(), CORE.mix({ getters: ['deviceTree'] })],

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 设备图片
     */
    deviceImg() {
      const { param, getImg } = this
      const matched = CORE.DICT.SUB_SYSTEM.find(([id]) => id === param.subSystemId)
      return matched ? getImg(matched[2], '_icon') : ''
    },
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听新增就绪
     */
    readyAdd(ready) {
      const { selectParam } = this
      if (ready) {
        selectParam.areaId = ''
      }
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 点击返回
     */
    toBack() {
      const { param } = this
      param.subSystemId = ''
    },

    /**
     * 切换结构树
     */
    toChange({ id, device }) {
      const { selectParam, param, treeMap, startSelect, setModal, setOne } = this

      if (device) {
        setModal('add')
        setOne({ ...device, subSystemId: param.subSystemId })
      } else {
        setModal()
        setOne()
        selectParam.areaId = id
        selectParam.subSystemId = param.subSystemId
        if (!treeMap[id][`device_${param.subSystemId}`]) startSelect()
      }
    },

    /**
     * 获取节点样式类
     */
    getNodeClass(data) {
      const { chosenId, list } = this
      if (list && data.disabled) return 'CoreWeb-EasyTree-disabled'
      if (this.param.subSystemId === chosenId) return 'CoreWeb-EasyTree-chosen'
      return null
    },

    /**
     * 获取图片
     */
    getImg: MyMap.methods.getImg,
  },
}
</script>
